package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itheima.entity.AddressBook;
import com.itheima.entity.Orders;
import com.itheima.entity.User;
import com.itheima.mapper.OrderMapper;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 订单实现类
 */
@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    //订单详情表业务接口
    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 下单
     *
     * @param orders
     */
    @Override
    public void save(Orders orders, HttpSession session) {
        log.debug("**下单**",orders.toString());
        User user = (User)session.getAttribute("user");
        //1 补全orders表中数据
        //1.1获取唯一的订单号 设置到orders表中number字段
        orders.setNumber(IdWorker.getId()+"");
        //1.2下单设置 2待派送    //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);
        //1.3 下单用户id userId 可以从ThreadLocal中获取当前用户id
        orders.setUserId(user.getId());
        //1.4 addressBookId payMethod amount remark(页面上传入的数据)
        //1.5 orderTime 设置当前时间为下单时间
        orders.setOrderTime(LocalDateTime.now());
        //1.6 checkoutTime 设置当前时间为结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1.7 userName user表中name值
        orders.setUserName(user.getName());
        //1.8 phone address consignee address_book地址薄表中phone手机号  address地址  consignee收货人名字
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());//收货人手机号
        orders.setAddress(addressBook.getDetail());//收货地址 实际项目中应该 将省市区拼接+详细信息
        orders.setConsignee(addressBook.getConsignee());//收货人
        log.debug("**保存订单数据**",orders.toString());
        //2 保存订单数据到orders表中
        orderMapper.insert(orders);
        Long ordersId = orders.getId();///订单表主键id 设置到订单详情表中orderId
        log.debug("**订单保存成功了**订单主键id为{}**",ordersId);
        //3 保存订单详情到order_detail表中
        orderDetailService.insert(ordersId);
        log.debug("**订单详情表保存成功了**");
    }
}
